package com.wgj.android.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jiaai.xui.utils.XDensityUtils;
import com.jiaai.xui.utils.XRegexUtils;
import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.ListHttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.utils.http.entity.VUpload;
import com.jiaai.xui.view.XTakePhotosDialog;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.entity.Card;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.widget.imageselect.ImagePicker;
import com.wgj.android.widget.imageselect.cropper.CropImage;
import com.wgj.android.widget.imageselect.cropper.CropImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.picker.SinglePicker;

/**
 * Created by Administrator on 2018/2/8.
 */

public class CreateCardActivity extends AppCompatActivity {
    @BindView(R.id.nickname)
    EditText nickname;
    @BindView(R.id.unit)
    EditText unit;
    @BindView(R.id.role)
    EditText role;
    @BindView(R.id.iphone)
    EditText iphone;
    @BindView(R.id.vx)
    EditText vx;
    @BindView(R.id.email)
    EditText email;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.intro)
    EditText intro;
    @BindView(R.id.uploadImgView)
    LinearLayout uploadImgView;
    @BindView(R.id.uploadImg)
    ImageView uploadImg;

    @BindView(R.id.avatar)
    ImageView avatar;
    @BindView(R.id.longitude)
    TextView longitude;
    @BindView(R.id.latitude)
    TextView latitude;

    private int size = 0;
    //private  JSONObject card;
    private Map<String, Object> dataMap = new HashMap<>();
    private SinglePicker<String> picker;
    private ImagePicker imagePicker;
    private List<String> images = new ArrayList<>();
    private Card card;
    private String add;
    //private String latitude;
    //private String longitude;
    private String avatarUrl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_new_card);
        /*if(getIntent().getExtras().containsKey("cards")){
            card=JSONObject.parseObject(getIntent().getExtras().getString("cards"));
        }*/
        card = (Card) getIntent().getSerializableExtra("card");
        //card1=new Card();
        imagePicker = new ImagePicker();
        // 设置标题
        imagePicker.setTitle("选择图片");
        // 设置是否裁剪图片
        imagePicker.setCropImage(true);
        ButterKnife.bind(this);
        XLoadingDialog.with(this).show();
        size = XDensityUtils.dp2px(80f);
        XHttp.obtain().get(WGJAPI.getCardTypeAll(), null, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {

                initTypePicker(s);
                if (card != null) {
                    bindData();
                }

                XLoadingDialog.with(CreateCardActivity.this).dismiss();
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XLoadingDialog.with(CreateCardActivity.this).dismiss();
                XToast.error("服务器异常");

            }

        });

    }

    private void initTypePicker(String s) {
        if (!TextUtils.isEmpty(s)) {
            JSONArray array = JSONArray.parseArray(s);
            ArrayList<String> types = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject object = array.getJSONObject(i);
                types.add(object.getString("name"));
            }
            //  types.add(0,"其它");
            picker = new SinglePicker<String>(this, types);
            picker.setCanLoop(false);//不禁用循环
            picker.setTopBackgroundColor(0xFFEEEEEE);
            picker.setTopHeight(50);
            picker.setSelectedIndex(0);
            picker.setTopLineColor(0xFF33B5E5);
            picker.setTopLineHeight(1);
            picker.setTitleText("请选择职称");
            picker.setTitleTextColor(0xFF999999);
            picker.setTitleTextSize(12);
            picker.setCancelTextColor(0xFF33B5E5);
            picker.setCancelTextSize(13);
            picker.setSubmitTextColor(0xFF33B5E5);
            picker.setSubmitTextSize(13);
            picker.setSelectedTextColor(0xFFEE0000);
            picker.setUnSelectedTextColor(0xFF999999);
            LineConfig config = new LineConfig();
            config.setColor(0xFFEE0000);//线颜色
            config.setAlpha(140);//线透明度
            config.setRatio((float) (1.0 / 8.0));//线比率
            picker.setLineConfig(config);
            picker.setItemWidth(200);
            picker.setBackgroundColor(0xFFE1E1E1);
            picker.setOnItemPickListener(new OnItemPickListener<String>() {
                @Override
                public void onItemPicked(int index, String item) {
                    type.setText(item);
                    // card.put("type",item);

                }
            });

        }
    }

    private void bindData() {
        nickname.setText(card.getNickname());
        unit.setText(card.getUnit());
        role.setText(card.getRole());
        iphone.setText(card.getIphone());
        vx.setText(card.getVx());
        email.setText(card.getEmail());
        type.setText(card.getType());
        address.setText(card.getAddress());
        longitude.setText(card.getLatitude());
        latitude.setText(card.getLongitude());
        intro.setText(card.getIntro());
        Glide.with(this).load(card.getAvatar()).into(avatar);
        if(card.getImg()!=null){
            JSONArray array = JSONArray.parseArray(card.getImg());
            for (int i = 0; i < array.size(); i++) {
                images.add(array.getString(i));
                addImageViewToLayout(array.getString(i));
            }
        }


    }

    @OnClick(R.id.type)
    public void onSelectType(View view) {
        if (picker != null) {
            //picker.setSelectedItem(card.containsKey("type") &&  TextUtils.isEmpty(card.getString("type"))?"其它":card.getString("type"));
            //picker.setSelectedItem(card.containsKey("type") &&  TextUtils.isEmpty(card.getString("type"))?"其它":" " + "");
            picker.show();
        }
    }

    @OnClick(R.id.avatar)
    public void onSelectAvater(View view) {
        selectImg(avatar);
    }

    @OnClick(R.id.uploadImg)
    public void onClickSelectImg(View view) {
        selectImg(uploadImg);
    }

    @OnClick(R.id.address)
    public void onOpenMa(View view) {
        MapActivity.toMapActivity(this);
        //startActivity(new Intent(this,TestActivity.class));
    }

    @OnClick(R.id.submit)
    public void onSubmit(View view) {
        if (nickname.getText().length() == 0) {
            XToast.error("请输入姓名");
            return;
        }
        if (unit.getText().length() == 0) {
            XToast.error("请输入单位名称");
            return;
        }
        if (role.getText().length() == 0) {
            XToast.error("请输入职称");
            return;
        }
        if (iphone.getText().length() == 0) {
            XToast.error("请输入手机号");
            return;
        }
        if (!XRegexUtils.checkMobile(iphone.getText().toString())) {
            XToast.error("请输入正确的手机号");
            return;
        }
        if (email.getText().length() == 0 || !XRegexUtils.checkEmail(email.getText().toString())) {
            XToast.error("请输入正确的E-Mail");
            return;
        }
        //dataMap.put("avater",card.containsKey("avater")?card.getString("avater"):"");
        dataMap.put("avatar", avatarUrl);
        dataMap.put("type", type.getText().toString());
        dataMap.put("email", email.getText().toString());
        dataMap.put("unit", unit.getText().toString());
        dataMap.put("role", role.getText().toString());
        dataMap.put("intro", intro.getText().toString());
        //dataMap.put("model",card.containsKey("model")&& TextUtils.isEmpty(card.getString("model"))?"model":card.getString("model"));
        dataMap.put("model", "#CC6633");
        dataMap.put("mId", CacheUtils.getMember().getM_id());
        //if(card.containsKey("id")){
        // dataMap.put("id",card.getInteger("id"));
        //}
        dataMap.put("nickname", nickname.getText().toString());
        dataMap.put("vx", vx.getText().toString());
        //dataMap.put("role",role.getText().toString());
        dataMap.put("iphone", iphone.getText().toString());
        Log.i("tianyun", new Gson().toJson(images));
        dataMap.put("img", new Gson().toJson(images));
        dataMap.put("address", address.getText());
        dataMap.put("longitude", longitude.getText());
        dataMap.put("latitude", latitude.getText());

        if (card != null) {
            dataMap.put("id", card.getId());
            editCard();
        } else {
            creatCard();
        }

    }

    private void creatCard() {
        XLoadingDialog.with(this).show();
        XHttp.obtain().post(WGJAPI.CREAT_CARD, dataMap, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                XToast.success("创建成功");
                XLoadingDialog.with(CreateCardActivity.this).dismiss();
                Intent intent = new Intent();
                setResult(1000, intent);
                finish();
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XToast.success("创建失败");
                XLoadingDialog.with(CreateCardActivity.this).dismiss();
            }
        });
    }

    private void editCard() {
        XLoadingDialog.with(this).show();
        XHttp.obtain().post(WGJAPI.UPDATE_CARD, dataMap, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                XToast.success("修改成功");
                XLoadingDialog.with(CreateCardActivity.this).dismiss();
                Intent intent = new Intent();
                setResult(1000, intent);
                finish();
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XToast.success("修改失败");
                XLoadingDialog.with(CreateCardActivity.this).dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == MapActivity.MAP_RESULTCODE) {
            if (data != null) {
                MapActivity.Location location = (MapActivity.Location) data.getSerializableExtra("location");
                longitude.setText(location.getLongitude()+"");
                latitude.setText(location.getLatitude()+"");
                address.setText(location.getAddress());
            }
            return;
        }
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
    }


    private void onUploadImage(final ImageView view, String path) {
        XLoadingDialog.with(this).show();
        Map<String, File> params = new HashMap<>();
        params.put("file", new File(path));
        XHttp.obtain().upload("wgj", params, new ListHttpCallBack<VUpload>() {
            @Override
            public void onSuccess(final List<VUpload> list) {
                XLoadingDialog.with(CreateCardActivity.this).dismiss();
                String urlPath = list.get(0).getFilePath();


                switch (view.getId()) {
                    case R.id.avatar:
                        Glide.with(CreateCardActivity.this).load(urlPath).into(avatar);
                        //card.put("avater",urlPath);
                        // card.setAvatar(urlPath);
                        avatarUrl = urlPath;

                        break;
                    case R.id.uploadImg:
                        images.add(urlPath);
                        addImageViewToLayout(urlPath);
                        break;
                    default:
                        View rootView = (View) view.getParent();
                        images.remove(rootView.getTag().toString());
                        rootView.setTag(urlPath);
                        images.add(urlPath);
                        Glide.with(CreateCardActivity.this).load(urlPath).into(view);
                        break;
                }

            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XToast.error("上传图片失败");
                XLoadingDialog.with(CreateCardActivity.this).dismiss();
            }
        });

    }

    private void selectImg(final ImageView view) {
        new XTakePhotosDialog(this, R.style.dialog_setting).setTakePhotosListener(new XTakePhotosDialog.OnTakePhotosListener() {
            @Override
            public void onTakePictureClick() {
                imagePicker.startCamera(CreateCardActivity.this, new ImagePicker.Callback() {
                    @Override
                    public void onPickImage(Uri imageUri) {
                    }

                    // 自定义裁剪配置
                    @Override
                    public void cropConfig(CropImage.ActivityBuilder builder) {
                        builder
                                // 是否启动多点触摸
                                .setMultiTouchEnabled(false)
                                // 设置网格显示模式
                                .setGuidelines(CropImageView.Guidelines.OFF)
                                // 圆形/矩形
                                .setCropShape(CropImageView.CropShape.RECTANGLE)
                                // 调整裁剪后的图片最终大小
                                .setRequestedSize(360, 360)
                                // 宽高比
                                .setAspectRatio(1, 1);
                    }

                    @Override
                    public void onCropImage(Uri imageUri) {
                        onUploadImage(view, imageUri.getPath());
                    }
                });
            }

            @Override
            public void onChoosePictureClick() {
                imagePicker.startGallery(CreateCardActivity.this, new ImagePicker.Callback() {
                    @Override
                    public void onPickImage(Uri imageUri) {
                    }

                    // 自定义裁剪配置
                    @Override
                    public void cropConfig(CropImage.ActivityBuilder builder) {
                        builder
                                // 是否启动多点触摸
                                .setMultiTouchEnabled(false)
                                // 设置网格显示模式
                                .setGuidelines(CropImageView.Guidelines.OFF)
                                // 圆形/矩形
                                .setCropShape(CropImageView.CropShape.RECTANGLE)
                                // 调整裁剪后的图片最终大小
                                .setRequestedSize(360, 360)
                                // 宽高比
                                .setAspectRatio(1, 1);
                    }

                    @Override
                    public void onCropImage(Uri imageUri) {
                        onUploadImage(view, imageUri.getPath());
                    }
                });

            }
        }).show();
    }

    private void addImageViewToLayout(String path) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
        params.rightMargin = XDensityUtils.dp2px(5f);
        FrameLayout relativeLayout = new FrameLayout(this);
        relativeLayout.setLayoutParams(params);
        relativeLayout.setTag(path);
        FrameLayout.LayoutParams imgParams = new FrameLayout.LayoutParams(size, size);
        ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(imgParams);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImg((ImageView) v);
            }
        });
        relativeLayout.addView(imageView);
        FrameLayout.LayoutParams butParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, XDensityUtils.dp2px(25f));
        butParams.gravity = Gravity.BOTTOM;
        TextView button = new TextView(this);
        button.setLayoutParams(butParams);
        button.setBackgroundColor(Color.parseColor("#50000000"));
        button.setText("删除");
        button.setClickable(true);
        button.setTextColor(Color.WHITE);
        button.setGravity(Gravity.CENTER);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View root = (View) v.getParent();
                String path = root.getTag().toString();
                images.remove(path);
                uploadImgView.removeView(root);
                uploadImg.setVisibility(View.VISIBLE);
            }
        });
        relativeLayout.addView(button);
        uploadImgView.addView(relativeLayout, uploadImgView.getChildCount() - 1);
        Glide.with(this).load(path).into(imageView);
        if (uploadImgView.getChildCount() > 3) {
            uploadImg.setVisibility(View.GONE);
        }
    }


}
